import time
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

destUrl = "https://www.taobao.com"

class TaoBao:
    def __init__(self, url):
        self.url = url
        self.inited = False
        self.browser = None

    def init(self):
        if self.inited == False:
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument("--no-sandbox")
            chrome_options.add_argument("--disable-gpu")
            chrome_options.add_argument("--disable-dev-shm-usage")
            chrome_options.add_argument(
                'user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36')
            service = Service(executable_path='/usr/local/bin/chromedriver')

            self.browser = webdriver.Chrome(service=service, options=chrome_options)
            self.wait = WebDriverWait(self.browser, 1000)

            waitClass = "site-nav-user"
            self.browser.get(destUrl)

            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, waitClass)))
            loginDiv = self.browser.find_element(By.CLASS_NAME, "site-nav-sign")
            loginA = loginDiv.find_elements(By.TAG_NAME, "a")
            loginA[0].click()

            waitClass = "site-nav-login-info-nick"
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, waitClass)))

            self.inited = True

    def getOneData(self, text):

        results = []
        try:
            self.init()
            waitId = 'J_Toolkit'
            self.wait.until(EC.presence_of_element_located((By.ID, waitId)))

            input = self.browser.find_element(By.CLASS_NAME, 'search-suggest-combobox-imageSearch-input')
            input.clear()
            input.send_keys(text)
            input.send_keys(Keys.RETURN)
            time.sleep(0.2)

            handles = self.browser.window_handles

            for handle in handles:
                self.browser.switch_to.window(handle)
                if self.browser.title == text + '_淘宝':
                    break

            waitClass = 'next-pagination'
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, waitClass)))

            mainImgClass = "//div[contains(@class, 'search-content-col')]//*[contains(@class, 'mainImg')]"
            titleClass = "//div[contains(@class, 'search-content-col')]//*[contains(@class, 'title')]"
            priceIntClass = "//div[contains(@class, 'search-content-col')]//*[contains(@class, 'priceInt')]"
            priceFloatClass = "//div[contains(@class, 'search-content-col')]//*[contains(@class, 'priceFloat')]"
            realSalesClass = "//div[contains(@class, 'search-content-col')]//*[contains(@class, 'realSales')]"

            mainImgs = self.browser.find_elements(By.XPATH, mainImgClass)
            titles = self.browser.find_elements(By.XPATH, titleClass)
            priceInts = self.browser.find_elements(By.XPATH, priceIntClass)
            priceFloats = self.browser.find_elements(By.XPATH, priceFloatClass)
            realSaleses = self.browser.find_elements(By.XPATH, realSalesClass)
            idx = 0
            for mainImg in mainImgs:
                item = {}
                item['img'] = mainImg.get_attribute("src")
                item['title'] = titles[idx].text
                item['price'] = priceInts[idx].text + priceFloats[idx].text
                item['sale'] = realSaleses[idx].text
                print(item)
                results.append(item)
                idx = idx + 1
        except Exception as e:
           print('出现异常:', e)

        result = {'code': 200, 'data': results}
        return result

    def __del__(self):
        if self.browser != None:
            self.browser.close()

taobao = TaoBao(destUrl)

#test
if __name__ == '__main__':
    taobao.getOneData('雨衣')
    del taobao